"use strict";

// Module encapsulating Hangout services.
var hangoutModule = angular.module('HangoutModule', []);

var stateHandlers = [];
var mockState = {};
function BroadcastStateChange(delta) {
	console.log("broadcast", delta);
	setTimeout(function(){
		console.log("timeout done", delta);
		var i = 0;
		for (i = 0; i < stateHandlers.length; ++i) {
			stateHandlers[i](mockState, delta);
		}
	}, 100);
}

// Service that registers a callback on an angular controller scope for Hangout state changes.
hangoutModule.factory('hangoutStateUpdateRegistration', function() {
	console.log("instantiating mock hangoutModule");
	var hangoutApiInstance = function(hangoutStateHandler) {
		// console.log(hangoutStateHandler, "Registering for Hangout state updates");
		stateHandlers.push(hangoutStateHandler);
	};
	return hangoutApiInstance; 
});

// Service that writes to Hangout state.
hangoutModule.factory('hangoutStateWriter', function() {
	console.log("instantiating mock hangoutStateWriter");
	var hangoutStateWriterInstance = function(key, val) {
		if (typeof key != "string") {
			console.log("invalid key type", key);
			return;
		} else if (typeof val != "string") {
			console.log("invalid val type", val);
			return;
		}
		console.log("setting '" + key + "' to '" + val + "'");
		mockState[key] = val;
		var delta = {};
		delta[key] = val;
		BroadcastStateChange(delta);
	}
	return hangoutStateWriterInstance;
});

hangoutModule.factory('hangoutView', function() {
	console.log("instantiating mock hangoutView");
	var hangoutViewInstance = new Object();
	hangoutViewInstance.getMyId = function() { return "ME"; };
	var meParticipant = new Object();
	meParticipant.id = "ME";
	var youParticipant = new Object();
	youParticipant.id = "YOU";
	hangoutViewInstance.getParticipants = function() { return [meParticipant, youParticipant]; };
	hangoutViewInstance.getStateVal = function(key) { 
		console.log("getting [" + key + "] = " + mockState[key]);
		if (key in mockState)
			return mockState[key];
		else
			return null;
	}
	hangoutViewInstance.getMyStateVal = function(key) {
		return hangoutViewInstance.getStateVal(key + "_" + hangoutViewInstance.getMyId());
	}
	hangoutViewInstance.getFullState = function() {
		return mockState;
	}
	hangoutViewInstance.iCanAddWork = function() {
		var my_work = hangoutViewInstance.getMyStateVal("work_requests");
		return (my_work == null || JSON.parse(my_work) == "");
	}
	hangoutViewInstance.registerApiReadyCallback = function(callback) {
		callback(null);
	}
	hangoutViewInstance.getMyStateVar = function(key) {
		return key + "_" + hangoutViewInstance.getMyId();
	}
	return hangoutViewInstance;
});

function initDeck() {
	mockState["master_view_ME"] = null;
	mockState["master_view_YOU"] = "ME";
};
initDeck();